<?php

/**
 * @Author: wuchenge
 * @Date: 2020-12-05 14:16:17
 * @email: ligui0506@sina.com
 * @descript: 角色节点
 */

namespace App\Models\Rbac;

use App\Models\Admin;
use App\Models\Model;
use DB;

class Role extends Model
{
    protected $table    = 'rbac_roles';
    protected $guarded  = ['id', 'created_at', 'updated_at'];
    protected $fillable = ['name'];

    /**
     * 关联节点
     * @return [type] [description]
     */
    public function nodes()
    {
        return $this->belongsToMany(Node::class, 'rbac_role_node', 'role_id', 'node_id');
    }

    /**
     * 关联管理员
     * @return [type] [description]
     */
    public function admins()
    {
        return $this->belongsToMany(Admin::class, 'rbac_role_admin', 'role_id', 'admin_id');
    }

    /**
     * 添加角色
     * @param  [type] $name [description]
     * @param  [type] $node [description]
     * @return [type]       [description]
     */
    public static function store($name, $node)
    {
        // 开启一个数据库事务
        $role = DB::transaction(function () use ($name, $node) {
            $role = self::create(['name' => $name]);
            if (!empty($node)) {
                // 关联节点
                $role->nodes()->attach($node);
            }

            return $role;
        });

        return $role;
    }

    // 修改角色
    public static function modify($role_id, $name, $node)
    {
        // 开启一个数据库事务
        $role = DB::transaction(function () use ($role_id, $name, $node) {
            $role = self::find($role_id);
            if (!$role) {
                return false;
            }

            $role->name = $name;
            $role->save();
            // 关联权限
            $role->nodes()->sync($node);

            return $role;
        });

        return $role;
    }

    // 删除角色
    public static function del($ids)
    {
        // 开启一个数据库事务
        $role = DB::transaction(function () use ($ids) {
            $model = self::whereIn('id', $ids);
            $model->get()->map(function (Role $role) {
                // 关联权限删除
                $role->nodes()->detach();
                $role->admins()->detach();
            });
            $model->delete();

            return true;
        });

        return $role;
    }
}
